<template>
  <view class="checkout-container">
    <!-- 顶部导航 -->
    <view class="checkout-header">
      <view class="title">订单结算</view>
      <view class="countdown" v-if="orderCreated">
        <text class="countdown-label">支付倒计时：</text>
        <text class="countdown-time">{{ formatTime(countdown) }}</text>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="address-card">
      <view class="section-title">
        <text class="bi bi-geo-alt"></text> 收货地址
      </view>
      <view class="address-content" v-if="defaultAddress">
        <view class="contact">{{ defaultAddress.name }} {{ defaultAddress.phone }}</view>
        <view class="address-detail">
          {{ defaultAddress.province }}{{ defaultAddress.city }}{{ defaultAddress.district }}{{ defaultAddress.detail }}
        </view>
      </view>
    </view>

    <!-- 订单商品 -->
    <view class="order-card">
      <view class="section-title">
        <text class="bi bi-bag"></text> 订单商品
      </view>
      <view class="order-items">
        <view 
          v-for="(item, index) in cartItems" 
          :key="index"
          class="order-item"
        >
          <view class="item-image">
            <image :src=" url('sp', item.id-1, 'png')" mode="aspectFill"></image>
          </view>
          <view class="item-info">
            <view class="item-title">{{ item.title }}</view>
            <view class="item-price-row">
              <view class="item-price">¥{{ item.price.toFixed(2) }}</view>
              <view class="item-quantity">x{{ item.quantity }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付信息 -->
    <view class="payment-card">
      <view class="section-title">
        <text class="bi bi-credit-card"></text> 支付信息
      </view>
      
      <view class="payment-item">
        <text>商品金额</text>
        <text class="price">¥{{ orderAmount.toFixed(2) }}</text>
      </view>
      
      <view class="payment-item">
        <text>运费</text>
        <text class="price">¥{{ shipping.toFixed(2) }}</text>
      </view>
      
      <!-- 优惠券选择 -->
      <view class="payment-item coupon-select" @tap="showCouponPicker">
        <text>优惠券</text>
        <view class="coupon-value">
          <text v-if="selectedCoupon" class="price">-¥{{ couponDiscount.toFixed(2) }}</text>
          <text v-else class="no-coupon">{{ availableCoupons.length }}张可用</text>
        </view>
      </view>
      
      <view class="payment-divider"></view>
      
      <view class="payment-item total">
        <text>应付金额</text>
        <text class="price-total">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>

    <!-- 账户余额 -->
    <view class="balance-card">
      <view class="section-title">
        <text class="bi bi-wallet2"></text> 账户信息
      </view>
      <view class="balance-items">
        <view class="balance-item">
          <text>卡号</text>
          <text class="balance">{{ userStore.userInfo.card }}</text>
        </view>
        <view class="balance-item">
          <text>当前余额</text>
          <text class="balance">¥{{ formatNumber(currentBalance) }}</text>
        </view>
      </view>
      
      <view class="balance-item" v-if="isBalanceEnough">
        <text>支付后余额</text>
        <text class="balance-after">¥{{  formatNumber(balanceAfterPayment) }}</text>
      </view>
      
      <view class="balance-warning" v-if="!isBalanceEnough">
        <text class="bi bi-exclamation-circle"></text>
        <text>余额不足，请前往线下充值后再支付</text>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="checkout-footer">
      <view class="total-amount">
        实付款：<text class="amount">¥{{ totalAmount.toFixed(2) }}</text>
      </view>
      <view class="action-btns">
        <button class="cancel-btn" @click="cancelOrder">取消订单</button>
        <button 
          class="pay-btn" 
          :disabled="!isBalanceEnough" 
          @click="payOrder"
        >
          确认支付
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useCartStore } from '@/stores/cartStore';
import { useUserStore } from '@/stores/userStore';

const url = $url;
const cartStore = useCartStore();
const userStore = useUserStore();

// 倒计时相关
const countdown = ref(60); // 60秒倒计时
const orderCreated = ref(false);
const timerId = ref(null);

// 订单相关
const cartItems = ref([]);
const shipping = ref(10); // 运费默认10元
const orderId = ref(''); // 订单ID
const selectedCoupon = ref(null); // 选中的优惠券

// 获取可用优惠券
const availableCoupons = computed(() => {
  const coupons = userStore.userInfo.coupons || [];
  return coupons.filter(coupon => 
    coupon.status === 'valid' && 
    orderAmount.value >= coupon.minSpend
  );
});

// 计算优惠券抵扣金额
const couponDiscount = computed(() => {
  return selectedCoupon.value ? selectedCoupon.value.amount : 0;
});

// 计算订单商品总额
const orderAmount = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity);
  }, 0);
});

// 计算订单总金额（含运费和优惠券）
const totalAmount = computed(() => {
  const amount = orderAmount.value + shipping.value;
  return Math.max(0, amount - couponDiscount.value);
});

// 获取默认地址
const defaultAddress = computed(() => {
  const addresses = userStore.userInfo.addresses || [];
  // 返回默认地址或第一个地址
  return addresses.find(addr => addr.isDefault) || addresses[0];
});

// 获取当前账户余额
const currentBalance = computed(() => {
  return userStore.userInfo?.balance || 0;
});

// 计算支付后余额
const balanceAfterPayment = computed(() => {
  return Number((currentBalance.value - totalAmount.value).toFixed(2));
});

// 判断余额是否足够
const isBalanceEnough = computed(() => {
  return currentBalance.value >= totalAmount.value;
});

// 格式化数字添加千位分隔符
const formatNumber = (num) => {
  // 先转换为数字并保留两位小数
  const fixedNum = Number(num).toFixed(2);
  // 分割整数和小数部分
  const parts = fixedNum.toString().split('.');
  // 只对整数部分添加千位分隔符
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return parts.join('.');
};

// 格式化倒计时时间
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 开始倒计时
const startCountdown = () => {
  orderCreated.value = true;
  timerId.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timerId.value);
      handleOrderTimeout();
    }
  }, 1000);
};

// 处理订单超时
const handleOrderTimeout = () => {
  uni.showToast({
    title: '支付超时，订单已取消',
    icon: 'none',
    duration: 2000
  });
  
  // 将订单加入到未付款订单中
  addToOrders('unpaid');
  
  // 延迟返回上一页
  setTimeout(() => {
    uni.navigateBack();
  }, 2000);
};

// 添加到用户订单列表
const addToOrders = (status) => {
  // 生成订单ID（使用时间戳+随机数）
  if (!orderId.value) {
    orderId.value = 'ORD' + Date.now().toString().slice(-8) + Math.floor(Math.random() * 1000);
  }
  
  // 构建订单对象
  const orderData = {
    id: orderId.value,
    items: cartItems.value,
    totalAmount: totalAmount.value,
    status: status, // 'paid' 已支付 或 'unpaid' 未支付
    address: defaultAddress.value,
    createTime: Date.now(),
    payTime: status === 'paid' ? Date.now() : null
  };
  
  // 添加到用户订单中
  userStore.addOrder(orderData);
  
  // 如果已支付，清空购物车
  if (status === 'paid') {
    cartStore.clearCart();
  }
};

// 取消订单
const cancelOrder = async () => {
  try {
    const success = await cartStore.clearCart();
    if (!success) {
      throw new Error('清空购物车失败');
    }
    uni.showToast({
      title: '订单已取消',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    console.error('取消订单失败:', error);
    uni.showToast({
      title: error.message || '取消订单失败',
      icon: 'none'
    });
  }
};

// 支付订单
const payOrder = async () => {
  if (!isBalanceEnough.value) {
    uni.showToast({
      title: '余额不足',
      icon: 'none'
    });
    return;
  }

  try {
    // 创建订单
    const order = {
      id: orderId.value,
      items: cartItems.value,
      totalAmount: totalAmount.value,
      shipping: shipping.value,
      couponDiscount: couponDiscount.value,
      address: defaultAddress.value,
      status: 'paid',
      createTime: new Date().toISOString()
    };

    // 调用云函数创建订单
    const result = await uniCloud.callFunction({
      name: 'orderManage',
      data: {
        action: 'create',
        account: userStore.userInfo.account,
        data: order
      }
    });

    if (!result.result || !result.result.success) {
      throw new Error(result.result?.message || '创建订单失败');
    }

    // 清空购物车
    const success = await cartStore.clearCart();
    if (!success) {
      throw new Error('清空购物车失败');
    }

    // 更新用户余额
    const updateResult = await uniCloud.callFunction({
      name: 'updateUserInfo',
      data: {
        account: userStore.userInfo.account,
        data: {
          balance: balanceAfterPayment.value
        }
      }
    });

    if (!updateResult.result || updateResult.result.status !== 1) {
      throw new Error(updateResult.result?.message || '更新余额失败');
    }

    // 更新本地用户信息
    userStore.updateUserInfo({
      ...userStore.userInfo,
      balance: balanceAfterPayment.value
    });

    uni.showToast({
      title: '支付成功',
      icon: 'success'
    });

    // 跳转到订单详情页
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/other/order/detail?id=${orderId.value}`
      });
    }, 1500);

  } catch (error) {
    console.error('支付失败:', error);
    uni.showToast({
      title: error.message || '支付失败',
      icon: 'none'
    });
  }
};

// 显示优惠券选择器
const showCouponPicker = () => {
  if (!availableCoupons.value.length) {
    uni.showToast({
      title: '暂无可用优惠券',
      icon: 'none'
    });
    return;
  }
  
  uni.showActionSheet({
    itemList: availableCoupons.value.map(coupon => 
      `满${coupon.minSpend}减${coupon.amount}`
    ),
    success: (res) => {
      selectedCoupon.value = availableCoupons.value[res.tapIndex];
    }
  });
};

// 初始化订单数据
const fetchCartData = async () => {
  try {
    const success = await cartStore.loadFromCloud();
    if (!success) {
      throw new Error('加载购物车数据失败');
    }
    cartItems.value = cartStore.cartItems;
    
    // 检查购物车是否为空
    if (cartItems.value.length === 0) {
      uni.showToast({
        title: '购物车为空',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
  } catch (error) {
    console.error('加载购物车数据失败:', error);
    uni.showToast({
      title: error.message || '加载购物车数据失败',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
};

onMounted(async () => {
  // 初始化订单数据
  await fetchCartData();
  
  // 生成订单ID
  orderId.value = 'ORD' + Date.now().toString().slice(-8) + Math.floor(Math.random() * 1000);
});

onBeforeUnmount(() => {
  // 清理定时器
  if (timerId.value) {
    clearInterval(timerId.value);
  }
});
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 180rpx;
}

.checkout-header {
  background: linear-gradient(135deg, #141E30 0%, #243B55 100%);
  color: #fff;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkout-header .title {
  font-size: 36rpx;
  font-weight: bold;
}

.countdown {
  background: rgba(255, 255, 255, 0.2);
  padding: 8rpx 16rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
}

.countdown-label {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.countdown-time {
  font-size: 28rpx;
  font-weight: bold;
  color: #FFD700;
}

.address-card,
.order-card,
.payment-card,
.balance-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}


.section-title .bi {
  font-size: 32rpx;
  color: var(--td-brand-color);
}

.address-content {
  padding: 20rpx 0;
}

.contact {
  font-size: 32rpx;
  margin-bottom: 10rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
}

.order-items {
  margin-top: 20rpx;
}

.order-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
  overflow: hidden;
  margin-right: 20rpx;
}

.item-image image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 28rpx;
  line-height: 1.4;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  font-size: 32rpx;
  color: #FF3B30;
  font-weight: bold;
}

.item-quantity {
  font-size: 26rpx;
  color: #666;
}

.payment-item,
.balance-item {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 0;
  font-size: 28rpx;
}

.payment-divider {
  height: 1px;
  background-color: #eee;
  margin: 16rpx 0;
}

.price, .balance {
  font-weight: bold;
  color: #333;
  margin-left: 4rpx;
}

.price-total {
  font-size: 36rpx;
  font-weight: bold;
  color: #FF3B30;
  margin-left: 4rpx;
}

.balance-after {
  font-weight: bold;
  color: #007AFF;
  margin-left: 4rpx;
}

.balance-warning {
  display: flex;
  align-items: center;
  background-color: #FFF3E0;
  padding: 16rpx;
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.balance-warning .bi {
  color: #FF9800;
  margin-right: 10rpx;
}

.checkout-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-amount {
  font-size: 28rpx;
}

.amount {
  font-size: 36rpx;
  font-weight: bold;
  color: #FF3B30;
  margin-left: 4rpx;
}

.action-btns {
  display: flex;
}

.cancel-btn,
.pay-btn {
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  margin-left: 20rpx;
  font-size: 30rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.pay-btn {
  background-color: #FF3B30;
  color: #fff;
}

.pay-btn[disabled] {
  background-color: #ccc;
  color: #fff;
}

.coupon-select {
  position: relative;
  cursor: pointer;
}

.coupon-select::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 16rpx;
  height: 16rpx;
  border-top: 4rpx solid #999;
  border-right: 4rpx solid #999;
  transform: translateY(-50%) rotate(45deg);
}

.coupon-value {
  display: flex;
  align-items: center;
}

.no-coupon {
  color: #999;
  font-size: 24rpx;
}
</style> 